
import requests
import asyncio
import aiohttp

async def check_ip_is_master_station(ip):
    '''检查ip是否是主站'''
    url = f"http://{ip}:8080/is_master_station"
    
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(url, timeout=0.5) as response:
                if response.status == 200:
                    text = await response.text()
                    if text.strip() == "true":
                        return True
    except Exception as e:
        print(f"{ip}: 不是主站")
        print(str(e))
    
    return False

async def scan_master_stations(ip_list):
    tasks = []
    for ip in ip_list:
        task = asyncio.ensure_future(check_ip_is_master_station(ip))
        tasks.append(task)
    
    results = await asyncio.gather(*tasks)
    
    master_stations = [ip for ip, result in zip(ip_list, results) if result]
    return master_stations

ip_list = ["192.168.31.121", "192.168.31.122", "192.168.31.123"]  # 需要扫描的IP列表

loop = asyncio.get_event_loop()
master_stations = loop.run_until_complete(scan_master_stations(ip_list))
print("主站IP列表：", master_stations)
